﻿using System;
using System.Text;
using Models = Evaluant.Uss.Models;
using Evaluant.Uss.DomainModel.OptionModel;
using Evaluant.Uss.SqlMapper;

namespace MappingGenerator
{
    public class TablePerSubClass : IMappingImpl
    {
        public TablePerSubClass(Models.Model model, Option option)
            : base(model, option)
        {
        }

        public override Mapping CreateMapping()
        {
            Mapping mapping = new Mapping();
            foreach (Models.Entity entity in _model.GetBaseEntities())
            {
                EntityOption parentEntityOption = GetEntityOption(entity.Type);

                string parentTable = parentEntityOption.TableName;

                EntityMapping parentEntityMapping = BuildEntityMapping(entity, parentEntityOption);

                mapping.Entities.Add(parentEntityMapping);

                foreach (Models.Entity child in _model.GetTree(entity.Type))
                {
                    if (child == entity)
                        continue;

                    EntityOption childEntityOption = GetEntityOption(child.Type);

                    EntityMapping childEntityMapping = BuildEntityMapping(child, childEntityOption);
                    childEntityMapping.Ids[0].Generator = new GeneratorMapping();
                    childEntityMapping.Ids[0].Field = parentEntityMapping.Ids[0].Field;
                    childEntityMapping.Ids[0].Generator.Name = GeneratorMapping.GeneratorType.inherited;

                    mapping.Entities.Add(childEntityMapping);
                }
            }

            foreach (Models.Reference relation in _model.GetAllReferences())
            {
                EntityMapping parentEntity = mapping.Entities[relation.ParentType];
                EntityMapping childEntity = mapping.Entities[relation.ChildType];

                BuildRelationshipMapping(relation, mapping, parentEntity, childEntity);
            }

            return mapping;
        }

    }
}
